#include "database_adhocstatement.h"

#include <cstdlib>
#include <cstring>

#include "report.h"
#include "database_mysql_connection.h"
#include "database_query_result.h"

namespace afcore {
namespace database {

CBasicStatementTask::CBasicStatementTask(const char* sql, bool async) {
  sql_ = strdup(sql);
  has_result_ = async;
  if (async) {
    result_ = new RQueryResultPromise();
  }
}

CBasicStatementTask::~CBasicStatementTask() {
  free((void*)sql_);
  if (has_result_ && nullptr != result_) {
    delete result_;
  }
}

bool CBasicStatementTask::Execute() {
  if (has_result_) {
    CResultSet* result = conn_->Query(sql_);
    if (!result || !result->GetRowCount() || !result->NextRow()) {
      delete result;
      result_->set_value(RQueryResultSptr(nullptr));
      return false;
    }

    result_->set_value(RQueryResultSptr(result));
    return true;
  }

  return conn_->Execute(sql_);
}

} // !namespace database
} // !namespace afcore